<script lang="jsx" setup>
import { getCurrentInstance, ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useAuthStore } from '@/store/modules/auth';
import Modal from '@/components/common/modal.vue';
import { get, post } from '@/service/api/api';
import underReview from '@/assets/imgs/examine-icon/under-review.png';
import unaudited from '@/assets/imgs/examine-icon/unaudited.png';
import audited from '@/assets/imgs/examine-icon/audited.png';

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => false
  },
  operateType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object,
    default: null
  }
});

const instance = getCurrentInstance();
const authStore = useAuthStore();
console.log('authStore :>> ', authStore);
console.log('props :>> ', props);
const emit = defineEmits(['addModalClose', 'addSuccess']);

const lotType = ref('searchInput');
const lotids = ref([]);
const topFormList = ref([
  {
    type: 'tabs',
    span: 24,
    name: '基础信息'
  },
  {
    type: lotType,
    key: 'lotId',
    label: 'Lot号',
    span: 8,
    rule: {
      required: true,
      message: '请输入Lot号',
      trigger: 'change'
    },
    searchKey: 'lotNumber',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    disabled: false,
    selectOptions: lotids,
    showSelectOtherBtn: true,
    selectOtherBtnText: '查询',
    search: true,
    handleSelectOtherBtnClick: () => {
      get('/rcerp/agv/erp/findByLotNo', {
        lotNumber: model.value.lotId
      }).then(({ data, error }) => {
        if (!error) {
          Object.keys(model.value).forEach(item => {
            model.value[item] = data[item] || model.value[item];
          });
        }
      });
    },
    handleSearch() {
      get('/rcerp/agv/erp/findByLotNo', {
        lotNumber: model.value.lotId
      }).then(({ data, error }) => {
        if (!error) {
          Object.keys(model.value).forEach(item => {
            model.value[item] = data[item] || model.value[item];
          });
        }
      });
    }
  },

  {
    type: 'searchInput',
    key: 'moduleNo',
    label: '生产型号',
    span: 8,
    rule: {
      required: true,
      message: '请输入生产型号',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    handleSearch() {
      get('/rcerp/agv/erp/findByModuleNo', {
        moduleNo: model.value.moduleNo
      }).then(({ data, error }) => {
        if (!error) {
          Object.keys(model.value).forEach(item => {
            model.value[item] = data[item] || model.value[item];
          });
          lotids.value = data.lotNo.map(item => {
            return {
              label: item.lotNo,
              value: item.lotNo
            };
          });
          lotType.value = 'select';
        }
      });
    }
  },
  {
    type: 'input',
    key: 'quantity',
    label: '数量',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    change() {
      model.value.immgoldArea = (
        (Number(model.value.meridional) * Number(model.value.zonal) * Number(model.value.quantity)) /
        1000000
      ).toFixed(3);

      model.value.eletricGoldAddArea = (
        Number.parseFloat(model.value.immgoldArea) + Number.parseFloat(model.value.eletricGoldAddArea)
      ).toFixed(3);
      console.log('model.value,', model.value);
    }
  },
  {
    type: 'input',
    key: 'meridional',
    label: '板长(mm)',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'zonal',
    label: '板宽(mm)',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'goldArea',
    label: '金面积%',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'eletricGoldAddArea',
    label: '累计面积㎡',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'input',
    key: 'electricGlodRequired',
    label: '金厚要求um',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },
  {
    type: 'inputSelect',
    key: 'glodTimeDensity',
    label: '金电流设定时间/密度',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        value: '18s/15A',
        label: '18s/15A'
      },
      {
        value: '15s/10A',
        label: '15s/10A'
      },
      {
        value: '20s/10A',
        label: '20s/10A'
      }
    ]
  },
  {
    type: 'input',
    key: 'electricNickelRequired',
    label: '镍厚要求um',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    }
  },

  {
    type: 'inputSelect',
    key: 'nickelTimeDensity',
    label: '镍电流设定时间/密度',
    span: 8,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        value: '850s/28A',
        label: '850s/28A'
      },
      {
        value: '850s/25A',
        label: '850s/25A'
      },
      {
        value: '750s/28A',
        label: '750s/28A'
      }
    ]
  },
  {
    type: 'datePicker',
    key: 'modifyTime',
    label: '时间',
    span: 8,
    rule: {
      required: true,
      message: '请选择进板时间',
      trigger: 'change'
    },
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    showTime: true
  },
  {
    type: 'radio',
    key: 'shiftType',
    label: '班别',
    span: 6,
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    selectOptions: [
      {
        label: '白班',
        value: '0'
      },
      {
        label: '夜班',
        value: '1'
      }
    ]
  },
  {
    type: 'textarea',
    key: 'remark',
    label: '备注',
    tansfromDisabled(operateType) {
      return operateType === 'look';
    },
    textareaRows: 1,
    span: 24
  },
  {
    type: 'tabs',
    span: 24,
    name: '人员信息'
  },
  {
    type: 'input',
    key: 'operator',
    label: '操作员',
    defaultValue: authStore.userInfo.user.nickName || authStore.userInfo.user.userName,
    disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'foreman',
    label: '领班审核',
    disabled: true,
    span: 8
  },
  {
    type: 'input',
    key: 'examiner',
    label: '主管审核',
    disabled: true,
    span: 8
  },

  {
    type: 'tabs',
    span: 24,
    name: '药水补加(分补与生产补加)'
  }
]);

const modelVisible = ref(props.visible);
const modleAddLoading = ref(false);
const topFormRef = ref(null);

const optionsList = [
  [
    {
      label: '虹喜AD-482'
    }
  ],
  [
    {
      label: '中天化石AR级H₂SO₄(98%)'
    },
    {
      label: '展化过硫酸钠(SPS)'
    }
  ],
  [
    {
      label: '美得力化工氨基磺酸'
    }
  ],
  [
    {
      label: '光华科技氨基磺酸镍'
    },
    {
      label: '金柯氯化镍'
    },
    {
      label: '美得力化工硼酸'
    }
  ],
  [
    {
      label: '虹喜Ni-103R'
    },
    {
      label: '虹喜Ni-WA'
    },
    {
      label: '虹喜Ni-103ADD'
    },
    {
      label: '虹喜Ni-103S'
    }
  ],
  [
    {
      label: '英轩一水柠檬酸'
    }
  ],
  [
    {
      label: '虹喜Au-802A'
    },
    {
      label: '虹喜Au-802B'
    },
    {
      label: '虹喜Au-802C'
    },
    {
      label: '虹喜Au-802R'
    }
  ]
];
const addListNames = ['除油', '微蚀', '磺酸洗', '镍缸', '镍缸光剂', '酸活化', '金缸'];
const addList = ref(getAddList());

function getAddList() {
  const arr = [];
  for (let i = 0; i <= 6; i++) {
    arr.push({
      key: `potionAdd${i + 1}`,
      name: addListNames[i],
      options: optionsList[i],
      list: [
        {
          addName: null,
          addNum: null,
          addId: null,
          delFlag: null,
          electroGoldProduceId: null
        }
      ]
    });
  }
  return arr;
}

function getLookAndEditAddList() {
  const arr = [];
  for (let i = 0; i <= 6; i++) {
    arr.push({
      key: `potionAdd${i + 1}`,
      name: addListNames[i],
      options: optionsList[i],
      list: props.rowData[`potionAdd${i + 1}`]
    });
  }
  return arr;
}

function add(index) {
  addList.value[index].list.push({
    addName: null,
    addNum: null,
    addId: null,
    delFlag: null,
    electroGoldProduceId: null
  });
}

function del(index, index2) {
  addList.value[index].list.splice(index2, 1);
}

function getModel(arr) {
  const obj = {};
  arr.forEach(item => {
    obj[item.key] = item.defaultValue || null;
    if (props?.rowData) {
      obj[item.key] = props?.rowData?.[item.key];
    }
    if (item.tansfromDisabled) {
      item.disabled = item.tansfromDisabled(props.operateType);
    }
  });
  return obj;
}

const model = ref(getModel(topFormList.value));

async function handleOk(type) {
  const form = { ...topFormRef.value };
  const potionAddObj = {};

  // addList.value.forEach(item => {
  //   potionAddObj[item.key] = item.list;
  // });

  for (let i = 0; i < addList.value.length; i++) {
    const item = addList.value[i];
    for (let j = 0; j < item.list.length; j++) {
      const jItem = item.list[j];
      if (jItem.addName && (jItem.addNum === null || jItem.addNum === 0)) {
        message.error(`${item.name}添加数量不能为空`);
        return;
      }
      if (jItem.addNum && !jItem.addName) {
        message.error(`${item.name}不能为空`);
        return;
      }
    }
    potionAddObj[item.key] = item.list.map(k => {
      return {
        ...k,
        addName: k.addName || '',
        addNum: k.addNum || ''
      };
    });
  }
  await form.validateForm();

  const params = {
    ...model.value,
    ...potionAddObj
  };
  const msgObj = {
    add: '新增',
    edit: '修改'
  };
  let url = '/qms/electroGold/produce/add';
  params.time = dayjs(model.value.modifyTime).format('YYYY-MM-DD HH:mm:ss');
  if (props.rowData) {
    params.createTime = model.value.modifyTime;
    params.id = props.rowData.id;
    url = '/qms/electroGold/produce/update';
  }
  modleAddLoading.value = true;
  post(url, params)
    .then(({ error }) => {
      if (!error) {
        message.success(`${msgObj[props.operateType]}成功`);
        const obj = { ...instance.parent.refs.commonSearchRef, ...instance.parent.refs.tableRef };
        obj.formReset();
        obj.tableSelectChange([]);
        handleClose();
      }
    })
    .finally(() => {
      modleAddLoading.value = false;
    });
}

function handleClose() {
  modelVisible.value = false;
  model.value = getModel(topFormList.value);
  emit('addModalClose');
}

watch(
  () => props.visible,
  val => {
    modelVisible.value = val;
    if (val) {
      topFormList.value.forEach(item => {
        if (item.tansfromDisabled) {
          item.disabled = item.tansfromDisabled(props.operateType);
        }
      });
      getAddList();
      Object.keys(model.value).forEach(item => {
        if (props.rowData) {
          model.value[item] = props.rowData[item];
        } else {
          model.value[item] = null;
        }
      });

      if (props.operateType !== 'add') {
        model.value.modifyTime = props.rowData.createTime;
        addList.value = getLookAndEditAddList();
      } else {
        addList.value = getAddList();
      }
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <Modal
    v-model:visible="modelVisible"
    :title="`${{ add: '新增', edit: '编辑', look: '查看' }[props.operateType]}1#电金线生产记录表`"
    height="90vh"
    width="70vw"
    :destroy-on-close="true"
    :centered="true"
    @close="handleClose"
  >
    <div class="single-FQC-add-form h-full">
      <div v-if="props.operateType !== 'add'" class="state">
        <template v-if="props.rowData.state === 0">
          <img :src="unaudited" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 2 || props.rowData.state === 4">
          <img :src="underReview" alt="examine-icon" />
        </template>
        <template v-if="props.rowData.state === 3">
          <img :src="audited" alt="examine-icon" />
        </template>
      </div>
      <div ref="formBoxRef" class="form w-full">
        <Form ref="topFormRef" v-model:model="model" :form-list="topFormList"></Form>
      </div>
      <div class="add-list w-full">
        <AForm class="my-from w-full" :label-col="{ lg: 8, xs: 4 }" label-wrap>
          <div v-for="(item, index) in addList" :key="index" class="row">
            <template v-for="(v, index2) in item.list" :key="index2">
              <div class="w-full flex flex-center gap-15px">
                <div class="input-box flex gap-15px">
                  <div class="form-item w-50%">
                    <AFormItem :label="item.name" :label-col="{}">
                      <ASelect
                        v-model:value="v.addName"
                        placeholder="请选择"
                        size="small"
                        :disabled="props.operateType === 'look'"
                      >
                        <ASelectOption
                          v-for="o in item.options"
                          :key="o.label"
                          :label="o.label"
                          :value="o.label"
                        ></ASelectOption>
                      </ASelect>
                    </AFormItem>
                  </div>
                  <div class="form-item w-50%">
                    <AFormItem label="添加数量" :label-col="{}">
                      <AInput v-model:value="v.addNum" size="small" :disabled="props.operateType === 'look'"></AInput>
                    </AFormItem>
                  </div>
                </div>
                <div class="btn-box w-150px flex flex-center">
                  <AButton type="primary" size="small" :disabled="props.operateType === 'look'" @click="add(index)">
                    新 增
                  </AButton>
                  <AButton
                    type="primary"
                    size="small"
                    class="ml-8px"
                    :disabled="props.operateType === 'look'"
                    @click="del(index, index2)"
                  >
                    删 除
                  </AButton>
                </div>
              </div>
            </template>
          </div>
        </AForm>
      </div>
    </div>
    <template #footer>
      <div class="modal-footer">
        <AButton v-if="props.operateType == 'add'" type="primary" :loading="modleAddLoading" @click="handleOk('add')">
          保 存
        </AButton>
        <AButton v-if="props.operateType == 'edit'" type="primary" :loading="modleAddLoading" @click="handleOk('edit')">
          修 改
        </AButton>
        <AButton @click="handleClose">关 闭</AButton>
      </div>
    </template>
  </Modal>
</template>

<style lang="scss" scoped>
.single-FQC-add-form {
  border: 1px solid #ccc;
  padding: 0 30px;
  overflow: auto;
  padding-top: 15px;
  position: relative;

  .state {
    position: absolute;
    top: 0;
    right: 100px;
    img {
      height: 80px;
    }
  }
  .add-list {
    padding: 15px;

    .row {
      .input-box {
        width: calc(100% - 165px);
      }
    }

    .my-from {
      :deep(.ant-form-item) {
        margin-bottom: 5px;
      }
    }
  }
}
</style>
